﻿
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsApplication1.Helper
{
    public  class CFunction
    {
        public static string getrolelea(string pid, DataTable dt, string Beginstring, string childid, string childtext)
        {
            StringBuilder sb = new StringBuilder();
            DataRow[] rows;
            if (pid == null)
            {
                rows = dt.Select(Beginstring + " is null ");
            }
            else
            {
                rows = dt.Select(Beginstring + "='" + pid + "'");
            }
            sb.Append("[");
            bool isFist = false;
            foreach (DataRow dr in rows)
            {
                if (isFist)
                    sb.Append(",");
                isFist = true;
                string id = dr[childid].ToString();
                sb.Append("{");
                sb.AppendFormat("\"id\":\"{0}\",", dr[childid]);
                sb.AppendFormat("\"text\":\"{0}\",", dr[childtext]);
                sb.AppendFormat("\"url\":\"{0}\",", dr["Url"]);
                sb.Append("\"children\":[");
                sb.Append(GetSubroleMenu(id, dt, Beginstring, childid, childtext));
                sb.Append("]");
                sb.Append("}");
            }
            sb.Append("]");
            string result = sb.ToString();

            return result;
        }
        public static string GetSubroleMenu(string pid, DataTable dt, string Beginstring, string childid, string childtext)
        {
            StringBuilder sb = new StringBuilder();
            DataRow[] rows = dt.Select(Beginstring + "='" + pid + "'");
            if (rows.Length > 0)
            {
                bool isFist = false;
                foreach (DataRow dr in rows)
                {
                    if (isFist)
                        sb.Append(",");
                    isFist = true;
                    string id = dr[childid].ToString();
                    sb.Append("{");
                    sb.AppendFormat("\"id\":\"{0}\",", dr[childid]);
                    sb.AppendFormat("\"text\":\"{0}\",", dr[childtext]);
                    sb.AppendFormat("\"url\":\"{0}\",", dr["Url"]);                
                    sb.Append("\"children\":[");
                    sb.Append(GetSubroleMenu(id, dt, Beginstring, childid, childtext));
                    sb.Append("]");
                    sb.Append("}");
                }
            }
            return sb.ToString();
        }

        public static string gettwo(string result)
        {
            if (result.Length == 1)
            {
                result = "0" + result;
            }

            return result;
        }



        public static void writetxt(string text)
        {

            text = text + "\n\r";
            DateTime now = DateTime.Now;
            string datetime = now.Year.ToString() + gettwo(now.Month.ToString()) + gettwo(now.Day.ToString()) + ".txt";
            string txtpath = ConfigurationManager.ConnectionStrings["txtpath"].ToString();
            string path = txtpath + datetime;
            if (!System.IO.File.Exists(path))
            {
                FileStream stream = System.IO.File.Create(path);
                stream.Close();
                stream.Dispose();
            }
            using (StreamWriter writer = new StreamWriter(path, true))
            {
                writer.WriteLine(text);
            }
        }
        

        public static System.Text.Encoding GetType(string FILE_NAME)
        {
            FileStream fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);
            System.Text.Encoding r = GetType(fs);
            fs.Close();
            return r;
        }
        public static System.Text.Encoding GetType(FileStream fs)
        {
            /*byte[] Unicode=new byte[]{0xFF,0xFE};  
            byte[] UnicodeBIG=new byte[]{0xFE,0xFF};  
            byte[] UTF8=new byte[]{0xEF,0xBB,0xBF};*/

            BinaryReader r = new BinaryReader(fs, System.Text.Encoding.Default);
            byte[] ss = r.ReadBytes(3);
            r.Close();
            //编码类型 Coding=编码类型.ASCII;   
            if (ss[0] >= 0xEF)
            {
                if (ss[0] == 0xEF && ss[1] == 0xBB && ss[2] == 0xBF)
                {
                    return System.Text.Encoding.UTF8;
                }
                else if (ss[0] == 0xFE && ss[1] == 0xFF)
                {
                    return System.Text.Encoding.BigEndianUnicode;
                }
                else if (ss[0] == 0xFF && ss[1] == 0xFE)
                {
                    return System.Text.Encoding.Unicode;
                }
                else
                {
                    return System.Text.Encoding.Default;
                }
            }
            else
            {
                return System.Text.Encoding.Default;
            }
        }


        public static void DeleteFolder(string dir)
        {
            foreach (string d in Directory.GetFileSystemEntries(dir))
            {
                if (File.Exists(d))
                {
                    FileInfo fi = new FileInfo(d);
                    if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
                        fi.Attributes = FileAttributes.Normal;
                    File.Delete(d);//直接删除其中的文件  
                }
                else
                {
                    DirectoryInfo d1 = new DirectoryInfo(d);
                    if (d1.GetFiles().Length != 0)
                    {
                        DeleteFolder(d1.FullName);////递归删除子文件夹
                    }
                    Directory.Delete(d);
                }
            }
        }


        public static string ToJson(DataTable dt)
        {
            StringBuilder jsonString = new StringBuilder();
            jsonString.Append("[");
            DataRowCollection drc = dt.Rows;
            for (int i = 0; i < drc.Count; i++)
            {
                jsonString.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string strKey = dt.Columns[j].ColumnName;
                    string strValue = drc[i][j].ToString();

                    Type type = dt.Columns[j].DataType;
                    jsonString.Append("\"" + strKey + "\":");
                    strValue = StringFormat(strValue, type);
                    if (j < dt.Columns.Count - 1)
                    {
                        jsonString.Append(strValue + ",");
                    }
                    else
                    {
                        jsonString.Append(strValue);
                    }
                }
                jsonString.Append("},");
            }
            if (drc.Count > 0)
                jsonString.Remove(jsonString.Length - 1, 1);
            jsonString.Append("]");
            return jsonString.ToString();
        }


        private static string StringFormat(string str, Type type)
        {
            if (type == typeof(string))
            {
                str = String2Json(str);
                str = "\"" + str + "\"";
            }
            else if (type == typeof(DateTime) || type == typeof(DateTime?))
            {
                str = "\"" + str + "\"";
            }
            else if (type == typeof(bool))
            {
                str = str.ToLower();
            }
            else if (type == typeof(Guid))
            {
                str = "\"" + str + "\"";
            }
            else if (type != typeof(string) && string.IsNullOrEmpty(str))
            {
                str = "\"" + str + "\"";
            }
            return str;
        }
        private static string String2Json(String s)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < s.Length; i++)
            {
                char c = s.ToCharArray()[i];
                switch (c)
                {
                    case '\"':
                        sb.Append("\\\""); break;
                    case '\\':
                        sb.Append("\\\\"); break;
                    case '/':
                        sb.Append("\\/"); break;
                    case '\b':
                        sb.Append("\\b"); break;
                    case '\f':
                        sb.Append("\\f"); break;
                    case '\n':
                        sb.Append("\\n"); break;
                    case '\r':
                        sb.Append("\\r"); break;
                    case '\t':
                        sb.Append("\\t"); break;
                    default:
                        sb.Append(c); break;
                }
            }
            return sb.ToString();
        }

        public static string Datasettojson(DataSet dataset)
        {
            string strjson =    ToJson(dataset.Tables[0]);
            string result = "{\"total\": " + dataset.Tables[1].Rows[0][0] + ",\"rows\":" + strjson + "}";
            return result;
        }

        public static string Datasettojson(DataTable dt )
        {
            string strjson = ToJson(dt);
            return strjson;
        }


        public static List<T> DeserializeJsonToList<T>(string json) where T : class
        {
            JsonSerializer serializer = new JsonSerializer();
            StringReader sr = new StringReader(json);
            object o = serializer.Deserialize(new JsonTextReader(sr), typeof(List<T>));
            List<T> list = o as List<T>;
            return list;
        }

        public static String  DeserializeListToJosn<T>(List<T>  list) where T : class
        {
            System.Web.Script.Serialization.JavaScriptSerializer jss = new                                                                System.Web.Script.Serialization.JavaScriptSerializer();
            string result= jss.Serialize(list);
            return result;
        }

    }
}
